import React, { useEffect, useState } from 'react';
import {
  Card,
  CardActionArea,
  CardActions,
  CardContent,
  Button,
  CardHeader,
  Avatar,
  Typography,
  makeStyles,
  ButtonGroup,
} from '@material-ui/core';
import moment from 'moment';
import ThumbUpIcon from '@material-ui/icons/ThumbUp';
import ChatBubbleIcon from '@material-ui/icons/ChatBubble';
import MarkdownIt from 'markdown-it';
import { useHistory } from 'react-router-dom';
import { getPublishedArticlesByType } from '../api/actions/article';

const useStyles = makeStyles((theme) => ({
  icon: {
    width: 300,
    height: 300,
    color: theme.palette.secondary.main,
  },
  container: {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    minHeight: '50vh',
  },
  button: {
    margin: theme.spacing(2),
  },
  card: {
    marginBottom: theme.spacing(2.5),
  },
  post: {
    height: 200,
    overflow: 'hidden',
  },
  cardHeaderAction: {
    margin: 0,
  },
  notFound: {
    display: 'flex',
    alignItems: 'center',
  },
  actionButton: {
    marginRight: theme.spacing(2),
  },
}));

export default function ArticleList(props) {
  const { type, posts } = props;
  const classes = useStyles();
  const history = useHistory();

  const [postsState, setPostsState] = useState([]);
  const renderMarkdown = (markdown) => {
    const markdownIt = new MarkdownIt();
    return markdownIt.render(markdown);
  };
  const handleLookArticle = (id) => {
    history.push(`/article/${id}`);
  };
  useEffect(() => {
    if (type) {
      const fetchData = async () => {
        const result = await getPublishedArticlesByType({
          type,
        });
        setPostsState(result.data);
      };
      fetchData();
    }
  }, [type]);

  const currentPost = posts || postsState;

  if (Array.isArray(currentPost) && currentPost.length > 0) {
    return (
      <>
        {currentPost.map((post) => (
          <Card className={classes.card} key={post._id}>
            <CardHeader
              classes={{
                action: classes.cardHeaderAction,
              }}
              avatar={(
                <Avatar aria-label="recipe" className={classes.avatar}>
                  R
                </Avatar>
              )}
              action={(
                <Button size="small" color="primary" variant="outlined">
                  关注
                </Button>
              )}
              title={post.userInfo.name}
              subheader={moment(post.time).format('YYYY-MM-DD')}
            />
            <CardActionArea>
              <CardContent>
                <Typography gutterBottom variant="h5" component="h2">
                  {post.title}
                </Typography>
                <Typography
                  variant="body2"
                  color="textSecondary"
                  dangerouslySetInnerHTML={{
                    __html: renderMarkdown(post.post),
                  }}
                  component="p"
                  className={classes.post}
                />
              </CardContent>
            </CardActionArea>
            <CardActions>
              <ButtonGroup
                color="primary"
                aria-label="outlined primary button group"
              >
                <Button className={classes.actionButton} size="small" variant="text" disabled startIcon={<ThumbUpIcon />}>
                  {
                    Array.isArray(post.liked) ? post.liked.length : 0
                  }
                </Button>
                <Button className={classes.actionButton} size="small" variant="text" disabled startIcon={<ChatBubbleIcon />}>
                  {
                    Array.isArray(post.comment) ? post.comment.length : 0
                  }
                </Button>
              </ButtonGroup>
              <Button
                size="small"
                color="primary"
                onClick={() => {
                  handleLookArticle(post._id);
                }}
              >
                查看原文
              </Button>
            </CardActions>
          </Card>
        ))}
      </>
    );
  }
  return (
    <div className={classes.container}>
      <Typography variant="h2">暂无内容</Typography>
    </div>
  );
}
